package com.controller;

import java.util.Objects;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import com.entity.User;
import com.service.UserService;

/**
 * 用户认证相关接口
 */
@Controller
public class LoginController{
	
	@Autowired
	private UserService userService;
	
	
	/**
	 * 登录
	 * @return
	 */
	@GetMapping("/login")
	public String login() {
		return "/jsp/login.jsp";
	}
	
	/**
	 * 登录
	 * @param user
	 * @param request
	 * @return
	 */
	@PostMapping("/login")
	public String login(String username, String password, HttpServletRequest request) {
		User user = userService.getByUsernameAndPassword(username, password);
		if(Objects.nonNull(user)) {
			request.getSession().setAttribute("user", user);
			return "redirect:/user/list";
		}
		request.setAttribute("msg", "用户或密码错误");
		return login();
	}
	
	/**
	 * 注销
	 * @param user
	 * @param request
	 * @return
	 */
	@GetMapping("/logout")
	public String logout(HttpServletRequest request) {
		request.getSession().removeAttribute("user");
		return login();
	}
	
}